https://leetcode.cn/problems/kth-node-from-end-of-list-lcci/


/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */

// typedef struct ListNode LNode;
// int kthToLast(struct ListNode* head, int k){
//     //直接遍历
//     LNode* cur = head;
//     int len = 0;
//     while(cur->next)
//     {
//         cur = cur->next;
//         len++;
//     }
//     LNode* pcur = head;
//     int cot = len-k+1;
//     while(cot--)
//     {
//         pcur = pcur->next;
//     }
//     return pcur->val;
// }

//快慢指针
//先让fast走k步，然后让slow和fast一起走
typedef struct ListNode LNode;
int kthToLast(struct ListNode* head, int k){
    LNode * slow = head;
    LNode * fast = slow;
    while(k--)
    {
        if(fast)
        {
            fast= fast->next;
        }
    }
    while(fast)
    {
        slow = slow->next;
        fast = fast->next;
    }
    return slow->val;
}
